package com.example.util;

import com.alibaba.druid.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/7/28 15:08
 */
@Slf4j
public class HttpUtils {
    private HttpUtils() {}

    public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
        StringBuilder res = new StringBuilder();
        OutputStream os = null;
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            // 向服务端发送消息
            conn.setDoOutput(true);
            // 接收服务端的消息
            conn.setDoInput(true);
            conn.connect();
            if (!StringUtils.isEmpty(outputStr)) {
                os = conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }
            // 读取服务端返回的内容
            is = conn.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line;
            while((line = br.readLine()) != null) {
                res.append(line);
            }
        } catch (IOException e) {
            log.error("IO 异常: {}", e.getMessage());
        } finally {
            try {
                if (null != os) os.close();
                if (null != br) br.close();
                if (null != isr) isr.close();
                if (null != is) is.close();
            } catch (IOException e) {
                log.error("IO 流关闭失败: {}", e.getMessage());
            }
        }
        return res.toString();
    }

    public static void main(String[] args) {
        String get = httpRequest("http://39.106.116.109:8082/article/list?pageSize=10&page=1&sort=created&order=desc&status=1", "GET", null);
        System.out.println(get);
        System.out.println(ResponseUtils.ok());
    }
}
